﻿using System.Reflection;

namespace Inscriptionem.Extensions
{
    public static class ObjectExtensions
    {
        private static BindingFlags RegularBindingFlags = BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.Public;
        private static BindingFlags OverrideBindingFlags = BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.DeclaredOnly;

        public static void CopyTo(this object Value, object Receiver)
        {
            foreach (PropertyInfo item in Value.GetType().GetProperties(RegularBindingFlags))
            {
                PropertyInfo valueProperty = item;
                PropertyInfo receiverProperty = null;

                try
                {
                    receiverProperty = Receiver.GetType().GetProperty(valueProperty.Name, RegularBindingFlags);
                }
                catch (AmbiguousMatchException ex)
                {
                    // Property is overriden
                    valueProperty = Value.GetType().GetProperty(valueProperty.Name, OverrideBindingFlags);
                    receiverProperty = Receiver.GetType().GetProperty(valueProperty.Name, OverrideBindingFlags);
                }

                if (receiverProperty != null)
                {
                    receiverProperty.SetValue(Receiver, valueProperty.GetValue(Value, null), null);
                }

            }
        }
    }
}